import AppHeader from "./components/AppHeader"
import AppFooter from "./components/AppFooter"
import AppSetting from "./components/AppSetting"
import { useEffect, useRef, useState } from "react"
import axios from "axios"
import $ipc from "./services/ipc/ipc.service"
import { message } from "antd"
import TaskList from "./components/task-list/TaskList"

function App(): JSX.Element {
  const [dragover, setDragover] = useState<boolean>(false)
  const dragOverRef = useRef<HTMLDivElement>(null)
  useEffect(() => {
    if (!dragOverRef.current) return
    dragOverRef.current.addEventListener("dragover", handleDragover)
    dragOverRef.current.addEventListener("dragleave", handleDragleave)
    dragOverRef.current.addEventListener("drop", handleDrop)
    
  }, [])
  function handleDragover(e: any) {
    e.preventDefault()
    setDragover(true)
  }
  function handleDragleave(e: any) {
    e.preventDefault()
    setDragover(false)

  }
  function handleDrop(e: any) {
    e.preventDefault()
    setDragover(false)
    const files = e.dataTransfer.files as FileList
    const validFiles: File[] = []
    for (let i = 0; i < files.length; i ++) {
      if (validFile(files[i])) {
        validFiles.push(files[i])
      }
    }
    if (validFiles.length < files.length || validFiles.length <= 0) {
      message.error("仅支持5M内的PNG/JPG/WEBP图片")
    }
    if (validFiles.length <= 0) return
    $ipc.registerTask(validFiles).subscribe(
      console.log
    )
  }
  function validFile(file: File): boolean {
    const maxSize = 5 * 1024 * 1024
    const validExts = ["png", "jpg", "jpeg", "webp"]
    const fileExt = (file.path.split(".").pop() || "").toLowerCase()
    const extValid = validExts.some(e => e === fileExt)
    const sizeValid = file.size < maxSize
    return extValid && sizeValid
  }
  return (
    <div ref={dragOverRef} className={`abs-full bg-gradient-to-b from-indigo-600 to-indigo-400 flex flex-col overflow-hidden ${dragover ? "dragover" : ""}`}>
      <AppHeader/>
      <div className="flex-1 relative">
        <TaskList/>
      </div>
      <AppFooter/>
      <AppSetting/>
    </div>
  )
}

export default App
